package com.device.service;

import com.device.entity.SerialPortConfig;
import com.device.entity.PollingConfig;
import com.device.entity.NetworkConfig;
import com.device.repository.SerialPortConfigRepository;
import com.device.repository.PollingConfigRepository;
import com.device.repository.NetworkConfigRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.UUID;

@Service
public class ConfigService {
    
    @Autowired
    private SerialPortConfigRepository serialPortConfigRepository;
    
    @Autowired
    private PollingConfigRepository pollingConfigRepository;
    
    @Autowired
    private NetworkConfigRepository networkConfigRepository;
    
    // Serial Port Config Methods
    public SerialPortConfig getSerialPortConfig(String deviceImei) {
        return serialPortConfigRepository.findByDeviceImei(deviceImei)
                .orElse(new SerialPortConfig(deviceImei));
    }
    
    public SerialPortConfig saveSerialPortConfig(SerialPortConfig config) {
        config.setUpdatedTime(System.currentTimeMillis());
        return serialPortConfigRepository.save(config);
    }

    public void deleteSerialPortConfig(String deviceImei) {
        Optional<SerialPortConfig> serialPortConfig = serialPortConfigRepository.findByDeviceImei(deviceImei);
        serialPortConfig.ifPresent(serialPortConfigRepository::delete);
    }
    
    // Polling Config Methods
    public PollingConfig getPollingConfig(String deviceImei) {
        return pollingConfigRepository.findByDeviceImei(deviceImei)
                .orElse(new PollingConfig(deviceImei));
    }
    
    public PollingConfig savePollingConfig(PollingConfig config) {
        config.setUpdatedTime(System.currentTimeMillis());
        return pollingConfigRepository.save(config);
    }

    public void deletePollingConfig(String deviceImei) {
        Optional<PollingConfig> pollingConfig = pollingConfigRepository.findByDeviceImei(deviceImei);
        pollingConfig.ifPresent(pollingConfigRepository::delete);
    }
    
    // Network Config Methods
    public NetworkConfig getNetworkConfig(String deviceImei) {
        return networkConfigRepository.findByDeviceImei(deviceImei)
                .orElse(new NetworkConfig(deviceImei));
    }
    
    public NetworkConfig saveNetworkConfig(NetworkConfig config) {
        config.setUpdatedTime(System.currentTimeMillis());
        return networkConfigRepository.save(config);
    }

    public void deleteNetworkConfig(String deviceImei) {
        Optional<NetworkConfig> networkConfig = networkConfigRepository.findByDeviceImei(deviceImei);
        networkConfig.ifPresent(networkConfigRepository::delete);
    }
} 